<template>
  <div class="el-tree-select-container">
    <el-select
      :value="selectedName"
      :placeholder="placeholder"
      :clearable="clearable"
      @clear="handleClear"
      @visible-change="handleVisibleChange"
      ref="select"
      filterable
      :filter-method="handleFilter"
      :popper-append-to-body="false"
      @input="handleSelectInput"
    >
      <el-option value="" class="el-tree-select-option">
        <el-input
          v-model="searchQuery"
          placeholder="搜索节点..."
          class="search-input"
          @input="handleSearch"
        ></el-input>

        <el-tree
          :data="filteredTreeData"
          :props="treeProps"
          :node-key="nodeKey"
          :default-expanded-keys="defaultExpandedKeys"
          :current-node-key="currentValue"
          @node-click="handleNodeClick"
          ref="tree"
          highlight-current
          :render-content="renderContent"
        ></el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: "ElTreeSelect",
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: "请选择...",
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    value: {
      type: String,
      default: "",
    },
    defaultSelectedId: {
      type: String,
      default: "",
    },
    nodeKey: {
      type: String,
      default: "id",
    },
    // 顶级节点（河流）的PID标识，默认为'0'
    riverPid: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      treeData: [],
      filteredTreeData: [],
      searchQuery: "",
      currentValue: "",
      selectedName: "",
      // 存储当前选中节点的完整信息
      selectedNode: null,
      treeProps: {
        children: "children",
        label: "name",
      },
      defaultExpandedKeys: [],
    };
  },
  watch: {
    data: {
      immediate: true,
      handler(newData) {
        this.treeData = this.buildTree(newData);
        this.filteredTreeData = [...this.treeData];
        this.$nextTick(() => {
          this.setDefaultSelection();
        });
      },
    },
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          // 验证传入的值是否为合法的子节点（非河流节点）
          if (!this.isRiverNode(newVal)) {
            this.currentValue = newVal;
            // 获取完整节点信息，包括PID
            this.selectedNode = this.findNodeById(this.treeData, newVal);
          } else {
            this.$nextTick(() => {
              this.setDefaultSelection();
            });
          }
        } else {
          this.selectedNode = null;
          this.$nextTick(() => {
            this.setDefaultSelection();
          });
        }
        this.updateSelectedName();
      },
    },
    currentValue(newVal) {
      this.updateSelectedName();
      // 当ID变化时，更新选中节点的完整信息
      this.selectedNode = newVal
        ? this.findNodeById(this.treeData, newVal)
        : null;
      this.$emit("input", newVal);
      // 同时发送包含ID和PID的完整信息
      this.$emit("change", {
        id: newVal,
        pid: this.selectedNode ? this.selectedNode.pid : null,
        node: this.selectedNode,
      });
    },
  },
  methods: {
    buildTree(data) {
      const nodeMap = {};
      const tree = [];

      data.forEach((node) => {
        nodeMap[node[this.nodeKey]] = { ...node, children: [] };
      });

      data.forEach((node) => {
        const currentNode = nodeMap[node[this.nodeKey]];
        if (node.pid === this.riverPid) {
          tree.push(currentNode);
        } else {
          const parentNode = nodeMap[node.pid];
          if (parentNode) {
            parentNode.children.push(currentNode);
          }
        }
      });

      return tree;
    },

    // 判断节点是否为河流节点（顶级节点）
    isRiverNode(nodeId) {
      const node = this.findNodeById(this.treeData, nodeId);
      return node && node.pid === this.riverPid;
    },

    setDefaultSelection() {
      // 优先级：defaultSelectedId（必须是非河流节点）> value > 自动选择最深子节点
      if (this.defaultSelectedId && !this.isRiverNode(this.defaultSelectedId)) {
        this.currentValue = this.defaultSelectedId;
        this.selectedNode = this.findNodeById(
          this.treeData,
          this.defaultSelectedId
        );
        return;
      }

      if (this.value && !this.isRiverNode(this.value)) {
        this.currentValue = this.value;
        this.selectedNode = this.findNodeById(this.treeData, this.value);
        return;
      }

      // 自动选择最深层次的子节点（排除河流节点）
      this.selectDeepestChildNode();
    },

    // 选择最深层次的子节点（非河流节点）
    selectDeepestChildNode() {
      if (!this.treeData || this.treeData.length === 0) return;

      // 步骤1：找到第一个有效的顶级节点（PID=riverPid，且id和name非空，排除无效节点）
      const firstValidTopNode = this.treeData.find(
        (node) =>
          node.pid === this.riverPid && node.id !== null && node.name !== null
      );
      if (!firstValidTopNode) return; // 无有效顶级节点，不处理

      // 步骤2：收集该顶级节点下的所有最后一级子节点（叶子节点）
      const leafNodes = [];
      const collectLeafNodes = (nodes) => {
        nodes.forEach((node) => {
          if (node.children && node.children.length > 0) {
            // 有子节点，递归深入
            collectLeafNodes(node.children);
          } else {
            // 无子女，是叶子节点，加入列表
            leafNodes.push(node);
          }
        });
      };
      collectLeafNodes(firstValidTopNode.children || []); // 仅处理第一个顶级节点的子节点

      // 步骤3：选中第一个叶子节点（如“污水处理厂二期”）
      if (leafNodes.length > 0) {
        const targetNode = leafNodes[0];
        this.currentValue = targetNode[this.nodeKey];
        this.selectedNode = targetNode;
      } else {
        // 若该顶级节点下无叶子节点，尝试选中其下第一个非顶级节点
        const firstChildNode = this.findFirstValidNode([firstValidTopNode]);
        if (firstChildNode) {
          this.currentValue = firstChildNode[this.nodeKey];
          this.selectedNode = firstChildNode;
        }
      }
    },

    // 查找第一个有效的非河流节点
    findFirstValidNode(nodes) {
      for (const node of nodes) {
        if (node.pid === this.riverPid) {
          // 顶级节点，递归查找其子节点
          if (node.children && node.children.length > 0) {
            const childResult = this.findFirstValidNode(node.children);
            if (childResult) return childResult;
          }
        } else {
          // 找到第一个非顶级节点
          return node;
        }
      }
      return null;
    },

    // 自定义节点渲染，使河流节点不可点击
    renderContent(h, { node }) {
      // 判断是否为河流节点
      const isRiver = node.data.pid === this.riverPid;

      return h(
        "span",
        {
          class: {
            "river-node": isRiver,
            "normal-node": !isRiver,
          },
          style: {
            cursor: isRiver ? "default" : "pointer",
            display: "block",
            width: "100%",
            padding: "6px 10px",
          },
        },
        [
          h("i", {
            class: {
              "fa fa-chevron-right":
                node.expanded === false &&
                node.children &&
                node.children.length,
              "fa fa-chevron-down":
                node.expanded === true && node.children && node.children.length,
              "fa fa-circle-o": !node.children || node.children.length === 0,
            },
            style: {
              marginRight: "8px",
            },
          }),
          h("span", node.label),
        ]
      );
    },

    updateSelectedName() {
      if (!this.currentValue || !this.selectedNode) {
        this.selectedName = "";
        return;
      }

      this.selectedName = this.selectedNode.name;
    },

    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node[this.nodeKey] === id) {
          return node;
        }
        if (node.children && node.children.length) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    handleNodeClick(node) {
      // 阻止选择河流节点
      if (node.pid === this.riverPid) {
        return;
      }

      const nodeId = node[this.nodeKey];
      this.currentValue = nodeId;
      this.selectedNode = node;
      this.selectedName = node.name;
      this.$refs.select.blur();
      this.searchQuery = "";
      this.filteredTreeData = [...this.treeData];
    },

    handleSearch() {
      if (!this.searchQuery) {
        this.filteredTreeData = [...this.treeData];
        this.defaultExpandedKeys = [];
        return;
      }

      const filteredNodes = [];
      const expandedKeys = new Set();

      const filterNode = (nodes, parentMatched = false) => {
        return nodes.reduce((acc, node) => {
          const nodeMatched = node.name
            .toLowerCase()
            .includes(this.searchQuery.toLowerCase());
          const childrenMatched =
            node.children &&
            filterNode(node.children, parentMatched || nodeMatched).length > 0;

          if (nodeMatched || parentMatched || childrenMatched) {
            const newNode = { ...node };
            if (node.children) {
              newNode.children = filterNode(
                node.children,
                parentMatched || nodeMatched
              );
            }
            acc.push(newNode);

            if (nodeMatched || childrenMatched) {
              expandedKeys.add(node[this.nodeKey]);
            }
          }

          return acc;
        }, []);
      };

      this.filteredTreeData = filterNode(this.treeData);
      this.defaultExpandedKeys = Array.from(expandedKeys);
    },

    handleFilter(query) {
      this.searchQuery = query;
      this.handleSearch();
    },

    handleClear() {
      this.currentValue = "";
      this.selectedNode = null;
      this.selectedName = "";
      this.searchQuery = "";
      this.filteredTreeData = [...this.treeData];
      this.defaultExpandedKeys = [];
      this.$emit("clear");
      this.$emit("input", "");
      this.$emit("change", {
        id: null,
        pid: null,
        node: null,
      });
    },

    handleVisibleChange(visible) {
      if (!visible) {
        this.searchQuery = "";
        this.filteredTreeData = [...this.treeData];
        this.defaultExpandedKeys = [];
      } else {
        if (this.currentValue) {
          this.expandToSelectedNode();
        }
      }
      this.$emit("visible-change", visible);
    },

    expandToSelectedNode() {
      if (!this.currentValue) return;

      const getAncestorIds = (node, targetId, ancestors = []) => {
        if (node[this.nodeKey] === targetId) {
          return [...ancestors, node[this.nodeKey]];
        }

        if (node.children && node.children.length) {
          for (const child of node.children) {
            const result = getAncestorIds(child, targetId, [
              ...ancestors,
              node[this.nodeKey],
            ]);
            if (result) return result;
          }
        }

        return null;
      };

      for (const node of this.treeData) {
        const ancestorIds = getAncestorIds(node, this.currentValue);
        if (ancestorIds) {
          this.defaultExpandedKeys = ancestorIds.slice(0, -1);
          break;
        }
      }
    },

    handleSelectInput(val) {
      if (!val) {
        this.handleClear();
      }
    },
  },
};
</script>

<style scoped>
.el-tree-select-container {
  width: 100%;
  max-width: 300px;
}

.search-input {
  padding: 8px 10px;
  margin: 5px;
  width: calc(100% - 10px);
}

.el-tree-select-option {
  padding: 0;
  height: auto;
  max-height: 300px;
  overflow-y: auto;
}

::v-deep .el-select-dropdown__item {
  padding: 0;
}

::v-deep .el-tree-node__content {
  height: auto;
  padding: 0;
}

::v-deep .el-select__input {
  display: none;
}

::v-deep .el-select__tags {
  max-width: 100%;
}

/* 河流节点样式 - 不可点击 */
::v-deep .river-node {
  color: #999;
  background-color: #f5f5f5;
}

/* 普通节点样式 - 可点击 */
::v-deep .normal-node:hover {
  background-color: #f5f7fa;
}
</style>
